// pages/ScenicArea/ScenicAreaCommitPage/index.js
var common = require("../../../public.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    buyerList: [], //购票人列表
    selectedBuyerList: [], // 选中的购票人
    couponList: [], // 可用优惠券列表
    currentCoupon: '', //选中的优惠券
    showBuyerPanel: false,
    showCouponsPanel: false,
    isLoadingBusy: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    let that = this
    wx.getStorage({
      key: 'user',
      success: function (res) {
        that.setData({
          userInfo: res.data.user,
          token: res.data.token,
          openid: res.data.openid,
          ticketId: options.ticketId,
          storeId: options.storeId,
          ticketName: options.ticketName,
          storeName: options.storeName,
          ticketPrice: options.ticketPrice,
          ticketNum: options.ticketNum,
          ticketTimeId: options.ticketTimeId,
          enterDate: options.enterDate,
          enterWeekday: options.enterWeekday,
          startTime: options.startTime,
          endTime: options.endTime,
          totalPrice: options.ticketPrice * 100 * options.ticketNum
        }, _ => {
          that.getBuyerList()
          that.getCoupon()
        })
      },
    })
  },
  getBuyerList() { // 获取购票人列表
    let that = this
    let tempJson = {
      userId: that.data.userInfo.id,
      token: that.data.token
    }
    common.post("/scenicTicket/ticketBuyer/getScenicTicketBuyerList", tempJson, function (res) {
      if (res.status === 200) {
        that.setData({
          buyerList: res.data
        })
      }
    })
  },
  getCoupon() { // 获取景区门票可用优惠券
    const that = this
    const tempJson = {
      userId: that.data.userInfo.id,
      token: that.data.token,
      ticketId: that.data.ticketId,
      buyNums: that.data.ticketNum
    }
    common.post("/order/getUserCityDiscountCouponForScenicTicket", tempJson, function (res) {
      if (res.status === 200) {
        that.setData({
          couponList: res.data
        })
      }
    })
  },
  selectBuyer(e) {
    console.log(e)
    let {
      index,
      item
    } = e.currentTarget.dataset

    let arrIndex = this.data.selectedBuyerList.indexOf(index)
    if (arrIndex != -1) { // 有

      let arr = this.data.selectedBuyerList
      arr.splice(arrIndex, 1)
      console.log(arr)
      this.setData({
        selectedBuyerList: arr
      })

    } else { // 没有
      if (this.data.selectedBuyerList.length < this.data.ticketNum) {
        this.setData({
          selectedBuyerList: [...this.data.selectedBuyerList, index]
        })
      }
    }
  },
  selectCoupon(e) {
    let {
      index,
      item
    } = e.currentTarget.dataset
    if (index == (this.data.currentCoupon.hasOwnProperty('index') ? this.data.currentCoupon.index : null)) { //再次点击已选中则取消选中
      this.setData({
        currentCoupon: '',
        totalPrice: this.data.ticketPrice * 100 * this.data.ticketNum
      })
    } else {
      this.setData({
        showCouponsPanel: false,
        totalPrice: this.data.totalPrice - item.discountsMoney * 100,
        currentCoupon: {
          index,
          item
        }
      })
    }
  },
  onSubmit() { // 提交订单
    const that = this
    if (that.data.selectedBuyerList.length != that.data.ticketNum) {
      wx.showToast({
        title: '请添加' + that.data.ticketNum + '位购票人信息',
        icon: 'none'
      })
      return;
    }
    let buyerList = []
    that.data.selectedBuyerList.map(index => {
      let buyerItem = {
        name: that.data.buyerList[index].name,
        phone: that.data.buyerList[index].phone,
        certificateNo: that.data.buyerList[index].certificateNo,
      }
      buyerList.push(buyerItem)
    })
    let tempJson = {
      userId: that.data.userInfo.id,
      token: that.data.token,
      storeId: that.data.storeId,
      couponNo: '',
      cityCouponNo: that.data.currentCoupon ? that.data.currentCoupon.item.couponNo : '',
      payment: that.data.totalPrice,
      ticketId: that.data.ticketId,
      ticketName: that.data.ticketName,
      ticketPrice: that.data.ticketPrice,
      ticketNum: that.data.ticketNum,
      ticketTimeId: that.data.ticketId,
      enterDate: that.data.enterDate,
      enterWeekday: that.data.enterWeekday,
      buyerList: buyerList
    }
    common.postJson("/ticketOrder/buyTicket", tempJson, function (res) {
      if (res.status == 200) {
        if (that.data.totalPrice == 0) {
          wx.navigateTo({
            url: '/pages/ScenicArea/ScenicAreaCommitPage/paySuccess/index?payment=' + that.data.totalPrice
          })
        } else {
          that.wxpay(res.data)
        }
      } else {
        common.showRequestErrMsg(res)
      }
    })
  },
  wxpay(orderId) { // 支付
    let that = this
    let tempJson = {
      orderId,
      userId: that.data.userInfo.id,
      token: that.data.token,
      openid: that.data.openid
    }
    common.wxPayRequest("/wxxcxPayForScenicTicket", tempJson, function (res) {
      wx.requestPayment({
        'timeStamp': res.data.timeStamp,
        'nonceStr': res.data.nonceStr,
        'package': res.data.package,
        'signType': res.data.signType,
        'paySign': res.data.paySign,
        'success': function (res) {
          common.showToast('支付成功', 'success')
          wx.navigateTo({
            url: '/pages/ScenicArea/ScenicAreaCommitPage/paySuccess/index?payment=' + that.data.totalPrice + '&orderId=' + orderId,
          })
        },
        'fail': function (res) {
          if (res.errMsg === 'requestPayment:fail cancel') {
            wx.redirectTo({
              url: '/pages/ScenicArea/ScenicAreaOrder/index?status=1',
            })
          } else {
            common.showToast(res.errMsg)
          }
        }
      })
    })

  },
  toAddBuyer() {
    wx.navigateTo({
      url: '/pages/ScenicArea/ScenicAreaAddBuyer/index',
    })
  },
  addBuyer() {
    this.setData({
      showBuyerPanel: true
    })
  },
  editBuyer(e) {
    let {
      item
    } = e.currentTarget.dataset
    console.log(item)

    wx.navigateTo({
      url: '/pages/ScenicArea/ScenicAreaAddBuyer/index?buyerInfo=' + JSON.stringify(item),
    })
  },
  closeBuyerPanel() {
    this.setData({
      showBuyerPanel: false
    })
  },
  openCouponsPanel() {
    this.setData({
      showCouponsPanel: true
    })
  },
  closeCouponsPanel() {
    this.setData({
      showCouponsPanel: false
    })
  }
})